<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>返回顶部</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .class1{
            height: 500px;
            background: lightblue;
        }
        .class2{
            height: 500px;
            background: lightcoral;
        }
        .class3{
            height: 500px;
            background: lightgreen;
        }
        .class4{
            height: 500px;
            background: lightsteelblue;
        }
        #to_top{
            position: fixed;
            right: 30px;
            bottom: 30px;
            width: 60px;
            height: 60px;
            font-size: 20px;
            font-family: '宋体';
            line-height: 60px;
            border:none;
            border-radius: 50%;
            cursor: pointer;
            background: rgba(0,0,0,0.3);
            color: black;
            display: none;
            outline: none;
        }
        #to_top:hover{
            background: rgba(0,0,0,0.6);
            color: white;
        }
    </style>
</head>
<body>
    <!-- 
    （1）DOM
        1、document.getElementById()
        2、document.documentElement.scrollTop和document.body.scrollTop为滚动条距离顶部距离
    （2）事件
        1、window.onscroll为监听页面滚动
        2、to_top.onclick单击事件
    （3）定时器的使用
        1、设置重复定时器，间隔为10ms，setInterval(function(){代码块},10)
        2、清除定时器clearInterval(timer),timer为时间标识符 
    -->
    <div class="class1"></div>
    <div class="class2"></div>
    <div class="class3"></div>
    <div class="class4"></div>
    <button id="to_top">↑</button>
    <script>
        var to_top = document.getElementById('to_top');
        var timer = null;//设置时间标识符
        to_top.onclick = function(){
            //设置定时器
            timer = setInterval(function(){
                var to_top_value = document.documentElement.scrollTop || document.body.scrollTop;
                //减小的速度
                var top_top_speed = Math.floor(-to_top_value/8);
                //滚动条上移
                document.documentElement.scrollTop = document.body.scrollTop = to_top_value + top_top_speed;
                //判断并清除定时器
                if(to_top_value <= 0){
                    clearInterval(timer)
                }
            },10)
        }
        //添加滚动监听
        window.onscroll = function(){
            var to_top_value = document.documentElement.scrollTop || document.body.scrollTop;
            if(to_top_value >= 600){
                to_top.style.display = 'block'
            }else{
                to_top.style.display = 'none'
            }
        }
    </script>
</body>
</html>